<?php
	/**
	*模型管理类
	**/
	class ModelClass {
		// 构造函数
		public function __constract(){
		}

		// 获取模型列表
		public function getList($data){
			global $db;

			// 获取所有数据
			$db->query("select
							model.id,
							model.name,
							model.create_time as createTime,
							model.description,
							model.listorder,
							model.table_name as tableName,
							user.name as createName
						from model
						left join admin_user as user
						on model.creator=user.id
						order by model.listorder asc, model.id asc", "");

			return $db->prepare->fetchAll();
		}

		// 添加模型
		public function add($data){
			global $db, $session;
			$loginUserId = $session->get("userId");
			$name = $data->name;
			$description = $data->description;
			$tableName = $data->tableName;
			$tableNameData = $tableName . '_data';
			$tableNameId = $tableName . "id";
			$fkTableNameId = "fk_" . $tableName . "id";
			$fkCatId = "fk_" . $tableName . "catid";

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			// 查询模型名称或者表名称是否已经存在
			$db->query("select * 
						from model
						where
							name=:name or
							table_name=:tableName
						for update",
						array(
							"name"=>$name,
							"tableName"=>$tableName
							)
						);
			$result = $db->prepare->fetchAll();
			if($result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "模型名称或者表名称已经存在了，请重新命名！", null);
			}

			// 插入一条新数据
			$db->query("insert into model(
							name,
							creator,
							table_name,
							description) 
						values(
							:name,
							:creator,
							:tableName,
							:description
						)", 
						array(
							"name"=>$name,
							"creator"=>$loginUserId,
							"description"=>$description,
							"tableName"=>$tableName
							)
						);

			// 主表和副表是否已经存在
			$db->query("select table_name from information_schema.tables 
						where 
							table_name =:tableName or 
							table_name =:tableNameData", 
							array(
								"tableName"=>$tableName,
								"tableNameData"=>$tableNameData
								));
			$result = $db->prepare->fetchAll();
			if($result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "主表和副表已经存在！", null);
			}

			$db->PDO->commit();
			// 事物结束

			// 生成模型主表
			$sql = "create table if not exists " . $tableName . "(
						  id int(11) not null auto_increment comment '主键',
						  catid int(11) not null comment '栏目id',
						  title varchar(50) not null comment '文章标题',
						  description text not null comment '文章描述',
						  pic varchar(255) not null comment '上传图片',
						  creator int(11) not null comment '创建者用户id',
						  recommend tinyint(1) not null comment '是否推荐',
						  create_time timestamp not null default current_timestamp comment '创建时间',
						  primary key (id,catid),
						  key " . $fkCatId . " (catid)
						)";
			$db->query($sql,"");
			// 生成外键依赖
			$sql = "alter table " . $tableName . "
						add constraint " . $fkCatId . " foreign key (catid) 
						references category (id) 
						on delete cascade 
						on update cascade";
			$db->query($sql,"");

			// 生成模型副表
			$sql = "create table if not exists " . $tableNameData . " (
						  id int(11) not null auto_increment comment '主键',
						  " . $tableNameId . " int(11) not null comment '栏目id',
						  content text not null comment '文章内容',
						  primary key (id," . $tableNameId . "),
						  key " . $fkTableNameId . " (" . $tableNameId . ")
						)";
			$db->query($sql,"");
			// 生成外键依赖
			$sql = "alter table " . $tableNameData . "
						add constraint " . $fkTableNameId . " foreign key (" . $tableNameId . ") 
						references " . $tableName . " (id) 
						on delete cascade 
						on update cascade";
			$db->query($sql,"");
		}

		// 更新模型
		public function edit($data){
			global $db;
			$id = $data->id;
			$name = $data->name;
			$description = $data->description;

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			// 判断id阐述是否有误
			$db->query("select * 
						from model
						where 
							id=:id
						for update",
						array(
							"id"=>$id
							));
			$result = $db->prepare->fetchAll();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "参数有误！", null);
			}

			// 更新数据
			$db->query("update model
						set
							name=:name,
							description=:description
						where
							id=:id",
						array(
							"id"=>$id,
							"name"=>$name,
							"description"=>$description
							)
						);
			$result = $db->prepare->rowCount();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "操作失败！", null);
			}

			$db->PDO->commit();
			// 事物结束
		}

		// 删除模型
		public function del($data){
			global $db;
			$id = $data->id;

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			// 模型里取出table_name表名
			$db->query("select table_name as tableName 
						from model
						where 
							id=:id",
						array(
							"id"=>$id
							));
			$result = $db->prepare->fetchAll();
			if(!$result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "参数有误！", null);
			}

			$tableName = $result[0]["tableName"];
			$tableNameData = $result[0]["tableName"] . "_data";

			// 判断栏目表是否有栏目引用模型
			$db->query("select * 
						from category
						where
							modelid=:modelId",
						array(
							"modelId"=>$id
							));
			$result = $db->prepare->fetchAll();
			if($result){
				$db->PDO->rollBack();
				returnAjaxJson(400, "栏目表里已经有栏目引用模型！", null);
			}

			// 删除modle_field表里引用模型的数据
			$db->query("delete from model_field
						where 
							modelid=:modelId",
						array(
							"modelId"=>$id
							)
						);

			// 删除modle表里的数据
			$db->query("delete from model
						where 
							id=:id",
						array(
							"id"=>$id
							)
						);

			$db->PDO->commit();
			// 事物结束

			// 删除主表和副表
			$sql = "drop table if exists " . $tableNameData;
			$db->query($sql,"");
			$sql = "drop table if exists " . $tableName;
			$db->query($sql,"");
		}

		// 排序
		public function order($data){
			global $db;
			$orderArr = $data;
			$len = count($orderArr);

			// 事务开始
			$db->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$db->PDO->beginTransaction();

			for($i=0; $i<$len; $i++){
				$item = $orderArr[$i];
				$listOrder = $item->listorder;
				$id = $item->id;
				// 更新数据
				$db->query("update model
							set
								listorder=:listorder
							where
								id=:id",
							array(
								"id"=>$id,
								"listorder"=>$listOrder
								)
							);
				$result = $db->prepare->rowCount();
				if(!$result){
					break;
					$db->PDO->rollBack();
					returnAjaxJson(400, "操作失败！", null);
				}
			}

			$db->PDO->commit();
			// 事物结束
		}

	}
?>